package cn.group.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@SessionAttributes(value = {"code"})
@RequestMapping("/code")
public class CodeController {

    @GetMapping("/getCode")
    public void getCode(Model model,HttpServletResponse resp) throws IOException {
        //通过工具类CaptchaUtil生成验证码，将验证码封装到CircleCaptcha对象里面
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(250, 50, 4, 15);
        //获取输出流，用于将验证码输出到页面
        ServletOutputStream outputStream = resp.getOutputStream();
        //将验证码写入到客户端
        captcha.write(outputStream);
        //获取验证码的字符串
        String code = captcha.getCode();
        //将验证码放入session域中
        model.addAttribute("code",code);
        //刷新输出流
        outputStream.flush();
        //关闭输出流
        outputStream.close();
    }

    @PostMapping("/checkCode")
    @ResponseBody
    public Map<String,Object> checkCode(@RequestParam("code") String inputCode, Model model) throws IOException {
        String rightCode = (String) model.getAttribute("code");
        /*System.out.println("输入验证码"+inputCode);
        System.out.println("真实验证码"+rightCode);*/
        Map<String,Object> map = new HashMap<>();
        if(inputCode.equalsIgnoreCase(rightCode)){
            //System.out.println("验证码验证成功");
            map.put("code","0");
        }else {
            //System.out.println("验证码验证失败");
            map.put("code","-1");
        }
        return map;
    }
}
